package net.xdclass.util;

import cn.hutool.json.JSONObject;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @author whg
 * @date 2025-05-15
 * @description
 */
public class ImageToBase64Rbj {

    public static String convertImageToBase64(String imagePath){
        try{
            Path path = Paths.get(imagePath);
            byte[] imageBytes = Files.readAllBytes(path);
            return Base64.getEncoder().encodeToString(imageBytes);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        List<String> nameList = new ArrayList<>();
        /*nameList.add("安徽--全电票");
        nameList.add("北京--增值税电子发票");
        nameList.add("湖南--医疗电子票1");
        nameList.add("湖南--医疗电子票2");
        nameList.add("上海--全电票");
        nameList.add("浙江--增值税");
        nameList.add("浙江--last");
        nameList.add("江苏--last");
        nameList.add("广东--last");
        nameList.add("四川");
        nameList.add("重庆1");
        nameList.add("重庆2");
        nameList.add("浙江3");
        nameList.add("浙江4");*/
        nameList.add("人保健");
        for (String name : nameList){
            generateSign(name);
        }
    }

    public static void generateSign(String name){
        //1、影像
        String filedata = convertImageToBase64("D:\\home\\rbj\\image\\"+ name +".png");
        String appId = "HSztV8CwbJV2YL5J";
        String fileid = UUID.randomUUID().toString().replace("-", "");
        String signCheck = "appid=" + appId +
                "&fileid=" + fileid +
                "&filedata=" + filedata;
        String md5Sign = MD5.md5_32(signCheck).toUpperCase();
        Map<String,String> map = new HashMap<>();
        map.put("fileid",fileid);
        map.put("filedata",filedata);
        map.put("sign",md5Sign);
        JSONObject jsonObject = new JSONObject(map);
        System.out.println(jsonObject);
        // 指定文件路径
        String filePath = "D:\\home\\rbj\\json\\"+ name +".txt";

        File file = new File(filePath);

        // 如果文件不存在，则创建文件
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                System.out.println("文件创建失败: " + e.getMessage());
                return;
            }
        }

        // 将 JSONObject 写入文件
        try (FileWriter fileWriter = new FileWriter(filePath)) {
            fileWriter.write(jsonObject.toString());
            System.out.println("JSONObject 已成功写入到文件: " + filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
